import useLocale from '@/composables/useLocale'
import { createI18n } from 'vue-i18n'
import hljs from 'highlight.js'
import markdownit from 'markdown-it'
import ClipboardJS from 'clipboard'
import { languages } from '../i18n'

const messages = Object.assign(languages)

const clipboard = new ClipboardJS('.markdown-it-copy-btn')

clipboard.on('success', () => {
    const locale = uni.getStorageSync('locale') || 'zh-CN'
    const i18n = createI18n({
        legacy: false,
        locale,
        fallbackLocale: 'en',
        messages,
    })
    const { t } = i18n.global
    uni.showToast({ title: t('copySuccess'), icon: 'none' })
})

const copyWrap =
    (render) =>
    (...args) => {
        const [tokens, idx] = args
        const content = tokens[idx].content
        const { t } = useLocale()
        const copyStr = t('copyCode')

        return render
            .apply(this, args)
            .replace(
                '</pre>',
                `<div><span data-clipboard-text="${content}" class="markdown-it-copy-btn cursor-pointer text-sm text-zinc-800">${copyStr}</span></div></pre>`,
            )
    }

const copy = (md) => {
    md.renderer.rules.code_block = copyWrap(md.renderer.rules.code_block)
    md.renderer.rules.fence = copyWrap(md.renderer.rules.fence)
}

export const md = markdownit({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return (
                    '<pre class="hljs-pre"><code class="hljs-code">' +
                    hljs.highlight(str, {
                        language: lang,
                        ignoreIllegals: true,
                    }).value +
                    '</code></pre>'
                )
            } catch (__) {
                /* empty */
            }
        }

        return (
            '<pre class="hljs-pre"><code class="hljs-code">' +
            md.utils.escapeHtml(str) +
            '</code></pre>'
        )
    },
})

md.use(copy)
